package jinyilw.swing.rlaf.ui;

import jinyilw.swing.rlaf.theme.RThemeColor;

import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicHTML;
import java.awt.Composite;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 * @author Jinyi
 */
public class RToggleButtonUI extends RButtonUI
{
	ButtonModel model;

	public static ComponentUI createUI(JComponent c)
	{
		return new RToggleButtonUI();
	}

	public RToggleButtonUI()
	{
		defaultAlpha = 0.4f;
		hoverAlpha = 0.5f;
	}

	@Override
	public void installUI(JComponent c)
	{
		super.installUI(c);
		model = b.getModel();
	}

	@Override
	public void update(Graphics g, JComponent c)
	{
		int h = b.getHeight(), w = b.getWidth();
		int arc = round > 0 ? round : (int) (h * 0.8);
		boolean isEnabled = b.isEnabled();
		boolean isRollover = model.isRollover();
		boolean isPressed = model.isPressed();
		boolean isSelected = model.isSelected();
		float alpha = !isEnabled ? 0.2f : isRollover ? hoverAlpha : defaultAlpha;

		Graphics2D g2d = (Graphics2D) g;
		Composite composite = g2d.getComposite();
		renderingConfig.setAllAAPainting(g2d);

		g2d.setComposite(alphaComposite.derive(alpha));

		if (isSelected)
			g2d.setPaint(new GradientPaint(1, 1, lightColor, 1, h - 1,
					RThemeColor.themeColor));
		else
			g2d.setColor(c.getBackground());
		g2d.fillRoundRect(1, 1, w - 2, h - 2, arc, arc);

		g2d.setComposite(alphaComposite.derive(isEnabled ? 0.8f : 0.25f));

		if (isEnabled && (isRollover || isSelected))
		{
			g2d.setColor(isSelected
					? RThemeColor.darkThemeColor
					: RThemeColor.themeColor);
		} else
		{
			GradientPaint borderPaint;
			if (isSelected)
				borderPaint = new GradientPaint(1, 1, lightBorderColor, 1,
						h - 1, RThemeColor.themeColor);
			else
				borderPaint = new GradientPaint(1, 1, lightBorderColor, 1,
						h - 1, darkBorderColor);
			g2d.setPaint(borderPaint);
		}

		g2d.drawRoundRect(1, 1, w - 2, h - 2, arc, arc);

		g2d.setComposite(alphaComposite.derive(isEnabled ? 1f : 0.35f));

		if (c.getClientProperty(BasicHTML.propertyKey) != null)
			RThemeColor.customForegroundSetting(c);

		if (isEnabled && isPressed)
			g2d.translate(0.8, 0.8);
		paint(g2d, c);
		if (isEnabled && isPressed)
			g2d.translate(-0.8, -0.8);
		renderingConfig.resetAllAAPainting(g2d);
		g2d.setComposite(composite);
	}
}
